package com.budwk.app.sqfwV2.service.publicSecurity;


import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.budwk.app.sqfw.constants.CommonConstants;
import com.budwk.app.sqfw.constants.SqfwFormSummaryConstants;
import com.budwk.app.sqfw.enums.DownLoadFileNameEnum;
import com.budwk.app.sqfw.enums.SqfwFormSummaryFieldEnum;
import com.budwk.app.sqfw.enums.SupportBusinessTypeEnum;
import com.budwk.app.sqfw.models.Sqfw_completeflow;
import com.budwk.app.sqfw.models.Sqfw_formSummary_new;
import com.budwk.app.sqfw.services.SqfwFormsummaryNewService;
import com.budwk.app.sqfwDoc.codeGenerator.pdfGenerate.AbstractCustomerPdfCreateField;
import com.budwk.app.sqfwDoc.codeGeneratorV2.fileParam.CommonParam;
import com.budwk.app.sqfwDoc.codeGeneratorV2.fileParam.CompleteFlowPdfParamForController;
import com.budwk.app.sqfwDoc.codeGeneratorV2.fileParam.PdfGenerateParam;
import com.budwk.app.sqfwDoc.codeGeneratorV2.generate.BasePdfGenerator;
import com.budwk.app.sqfwDoc.codeGeneratorV2.pdfService.CompleteFlowCommonPdfService;
import com.budwk.app.sqfwDoc.codeGeneratorV2.result.GeneratorPdfWordResult;
import com.budwk.app.sqfwV2.component.BinyangStreetComponent;
import com.budwk.app.sqfwV2.dto.dto.FireSafetyOnDayingRoadPdfDTO;
import com.budwk.app.sqfwV2.dto.entity.SqfwShopsBaseInfo;
import com.budwk.app.sqfwV2.dto.publicSecurity.PublicSecurityDTO;
import com.budwk.app.sqfwV2.generator.publicSecurity.pdf.PublicSecurityPdfGenerator;
import com.budwk.app.sqfwV2.service.ShopsBaseInfoService;
import com.budwk.app.sys.models.Sys_user;
import com.budwk.app.sys.services.SysUserService;
import com.budwk.app.util.DateUtils;
import com.budwk.app.util.StrUtil;
import com.budwk.app.util.poiUtils.nutzBeanUtils.NutzIocUtils;
import com.budwk.starter.security.utils.SecurityUtil;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.nutz.dao.Cnd;
import org.nutz.dao.util.cri.SqlExpressionGroup;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author 东方祥云低代码1.1
 * @since 2024-03-25
 * <p>
 * 大营路社会治安 1
 */
@IocBean
public class PublicSecurityPdfService extends CompleteFlowCommonPdfService {

    @Inject
    private ShopsBaseInfoService shopsBaseInfoService;

    @Inject
    private SysUserService userService;

    @Override
    public void createPdfAndMsg(CompleteFlowPdfParamForController paramForController) {
        super.createPdfAndMsg(paramForController);
    }

   /* @Override
    public void reCreatePdfAndMsg(String userId, String completeFlowId) {
        super.reCreatePdfAndMsg(userId, completeFlowId);
    }*/

    @Override
    public GeneratorPdfWordResult createPdfSync(CompleteFlowPdfParamForController paramForController) {
        return super.createPdfSync(paramForController);
    }

    /**
     * 获取用户自定义字段 代码生成器已经自动填充
     * 无需特殊修改
     *
     * @param paramData json字符串
     * @return 结果
     */
    @Override
    protected AbstractCustomerPdfCreateField getCustomerPdfField(String paramData) {
        return JSONObject.parseObject(paramData, PublicSecurityDTO.class);
    }

    /**
     * 允许用户自定义填充在创建pdf时所提供的数据
     *
     * @param pdfGenerateParam 创建pdf所提供的数据
     */
    @Override
    protected void customerPopularPdfGenerateParam(PdfGenerateParam pdfGenerateParam) {
        CommonParam customerParamMap = pdfGenerateParam.getCreateUserCommonParam();
        if (customerParamMap.getUnitName().contains(CommonConstants.DIRECTLY_UNDER)) {
            //Sys_user sysUser = userService.getUserById(SecurityUtil.getUserId());
            String unitName = customerParamMap.getProvince();
            if (!CommonConstants.DIRECTLY_UNDER.equals(customerParamMap.getCity())) {
                unitName += customerParamMap.getCity();
            }
            if (!CommonConstants.DIRECTLY_UNDER.equals(customerParamMap.getDistrict())) {
                unitName += customerParamMap.getDistrict();
            }
            if (!CommonConstants.DIRECTLY_UNDER.equals(customerParamMap.getCounty())) {
                unitName += customerParamMap.getCounty();
            }
            if (!CommonConstants.DIRECTLY_UNDER.equals(customerParamMap.getCommunity())) {
                unitName += customerParamMap.getCommunity();
            }
            customerParamMap.setUnitName(unitName);
        }

    }

    /**
     * 在这里设置生成pdf的所有generator
     *
     * @param pdfGenerateParam 创建pdf的参数
     * @return 生成pdf的generator合集
     */
    @Override
    protected List<BasePdfGenerator> getPdfGenerator(PdfGenerateParam pdfGenerateParam) {
        List<BasePdfGenerator> generatorList = Lists.newArrayList();
        // 在这里添加自己的generator
        // 例如 generatorList.add(new RefuseClassifyPdfGenerator());
        generatorList.add(new PublicSecurityPdfGenerator());
        return generatorList;
    }

    /**
     * 用户自定义下载pdf文件的名称
     *
     * @param pdfGenerateParam 创建pdf所提供的参数
     * @return 结果
     */
    @Override
    protected String getDownloadFileName(PdfGenerateParam pdfGenerateParam) {
        return DownLoadFileNameEnum.DYL_PUBLIC_SECURITY_STANDING_PDF.getName() + "_" + DateUtil.format(new Date(), "yyyyMMddHHmmss");
    }

    /**
     * 第五张表中的需要的类型，详情见 {@link com.budwk.app.sqfw.constants.SqfwFormSummaryConstants}
     *
     * @return 返回数据
     */
    @Override
    public String getSummaryType() {
        return SqfwFormSummaryConstants.public_security;
    }

    @Override
    protected void beforeInsertForSummary(Sqfw_formSummary_new formSummary) {
        // 1 校验基本信息

        // 2 保存商铺信息
        saveShopInfo(formSummary);
        // 3 组装数据
        buildFormSummary(formSummary);
    }

    private void buildFormSummary(Sqfw_formSummary_new formSummary) {
        String paramData = formSummary.getParamData();
        PublicSecurityDTO pdfDTO = JSONObject.toJavaObject(JSONObject.parseObject(paramData), PublicSecurityDTO.class);
        // 检查时间
        LocalDateTime inspectionDate = pdfDTO.getInspectionDate();
        if (inspectionDate != null) {
            formSummary.setFillDate(DateUtils.toDateByLocalDateTime(inspectionDate));
        }
        // 其他数据待补充


        PublicSecurityDTO f = StrUtil.serializerData(PublicSecurityDTO.class, pdfDTO);
        formSummary.setParamData(JSONObject.toJSONString(f));
    }

    protected void saveShopInfo(Sqfw_formSummary_new formSummary) {
        // 入库商铺
        String paramData = formSummary.getParamData();
        PublicSecurityDTO publicSecurityDTO = JSONObject.toJavaObject(JSONObject.parseObject(paramData), PublicSecurityDTO.class);
        //app2.0新字段通过上传的店铺id确定是一家
        if (StringUtils.isNotBlank(publicSecurityDTO.getShopInfoId())) {
            SqfwShopsBaseInfo s = this.shopsBaseInfoService.fetch(publicSecurityDTO.getShopInfoId());
            if (null != s) {
                if (StringUtils.isBlank(s.getServiceType())) {
                    s.setServiceType(SupportBusinessTypeEnum.PUBLIC_SECURITY.getCode());
                } else if (!s.getServiceType().contains(SupportBusinessTypeEnum.PUBLIC_SECURITY.getCode())) {
                    s.setServiceType(s.getServiceType() + "," + SupportBusinessTypeEnum.PUBLIC_SECURITY.getCode());
                }
                //原来是停业，巡检后改变状态
                if (SqfwFormSummaryFieldEnum.CHECK_STATUS_CLOSED.getCode().equals(s.getShopStatus())) {
                    s.setShopStatus(SqfwFormSummaryFieldEnum.check_status_checked.getCode());
                    s.setDeleted(false);
                }
                s.setUpdateId(SecurityUtil.getUserId());
                s.setUpdateDate(LocalDateTime.now());

                this.shopsBaseInfoService.updateIgnoreNull(s);
                formSummary.setShopsBaseInfoId(s.getId());
                return;
            }

        }

        SqfwShopsBaseInfo shopsBaseInfo = new SqfwShopsBaseInfo();

        shopsBaseInfo.setServiceType(SupportBusinessTypeEnum.PUBLIC_SECURITY.getCode());
        shopsBaseInfo.setPlaceName(publicSecurityDTO.getPlaceName());
        //shopsBaseInfo.setFillDate(DateUtil.toLocalDateTime(formSummary.getFillDate()));
        shopsBaseInfo.setOperator(publicSecurityDTO.getOperator());
        shopsBaseInfo.setOperatorTelephone(publicSecurityDTO.getOperatorTelephone());
        //shopsBaseInfo.setMainBusinessScope(publicSecurityDTO.getMainBusinessScope());
        shopsBaseInfo.setType(publicSecurityDTO.getPlaceType());
        shopsBaseInfo.setAddress(publicSecurityDTO.getAddress());
        Sys_user user = userService.fetch(SecurityUtil.getUserId());
        String detailAddress = String.format("%s%s%s%s%s%s%s", user.getProvince(), user.getCity(), user.getDistrict(),
                user.getCounty(), user.getCommunity(), shopsBaseInfo.getAddress(), shopsBaseInfo.getPlaceName());
        shopsBaseInfo.setDetailAddress(detailAddress);
        //shopsBaseInfo.setDetailAddress(publicSecurityDTO.getAddress());
        // 检查商铺数据是否存在 存在直接返回
        Cnd cnd = Cnd.NEW();
        SqlExpressionGroup sqlGroup = cnd.where();
        sqlGroup.andEquals(SqfwShopsBaseInfo::getProvince, user.getProvince());
        sqlGroup.andEquals(SqfwShopsBaseInfo::getCity, user.getCity());
        sqlGroup.andEquals(SqfwShopsBaseInfo::getDistrict, user.getDistrict());
        sqlGroup.andEquals(SqfwShopsBaseInfo::getCounty, user.getCounty());
        if (!CommonConstants.DIRECTLY_UNDER.equals(user.getCommunity())) {
            sqlGroup.andEquals(SqfwShopsBaseInfo::getCommunity, user.getCommunity());
        }
        if (StringUtils.isNotEmpty(shopsBaseInfo.getPlaceName())) {
            String placeName = shopsBaseInfo.getPlaceName().trim();
            sqlGroup.andEquals(SqfwShopsBaseInfo::getPlaceName, placeName);
            shopsBaseInfo.setPlaceName(placeName);
        }

        if (StringUtils.isNotEmpty(shopsBaseInfo.getAddress())) {
            String address = shopsBaseInfo.getAddress().trim();
            sqlGroup.andEquals(SqfwShopsBaseInfo::getAddress, address);
            shopsBaseInfo.setAddress(address);
        }

        //sqlGroup.andEquals(SqfwShopsBaseInfo::getType, type);
        //sqlGroup.andEquals(SqfwShopsBaseInfo::getDeleted, false);
        SqfwShopsBaseInfo s = this.shopsBaseInfoService.fetch(cnd);
        //SafeCheckTaskPdfDTO safeCheckTaskPdfDTO = JSONObject.parseObject(paramData, SafeCheckTaskPdfDTO.class);
        if (s != null) {
            // 不做五级更新
            s.setUpdateDate(LocalDateTime.now())
                    .setAddress(shopsBaseInfo.getAddress())
                    .setOperator(shopsBaseInfo.getOperator())
                    .setOperatorTelephone(shopsBaseInfo.getOperatorTelephone())
                    .setMainBusinessScope(shopsBaseInfo.getMainBusinessScope())
                    .setUpdateId(SecurityUtil.getUserId())
                    .setDeleted(false)
            //.setFillDate(DateUtil.toLocalDateTime(formSummary.getFillDate()))
            ;
            if (StringUtils.isBlank(s.getServiceType())) {
                s.setServiceType(SupportBusinessTypeEnum.PUBLIC_SECURITY.getCode());
            } else if (!s.getServiceType().contains(SupportBusinessTypeEnum.PUBLIC_SECURITY.getCode())) {
                s.setServiceType(s.getServiceType() + "," + SupportBusinessTypeEnum.PUBLIC_SECURITY.getCode());
            }
            //原来是停业，巡检后改变状态
            if (SqfwFormSummaryFieldEnum.CHECK_STATUS_CLOSED.getCode().equals(s.getShopStatus())) {
                s.setShopStatus(formSummary.getCheckStatus());
            }
            this.shopsBaseInfoService.updateIgnoreNull(s);
            formSummary.setShopsBaseInfoId(s.getId());
        } else {
            // 不存在 则新增
            shopsBaseInfo.setCreateDate(LocalDateTime.now())
                    .setUpdateDate(LocalDateTime.now())
                    .setCreateId(SecurityUtil.getUserId())
                    .setUpdateId(SecurityUtil.getUserId())
                    .setDeleted(false)
                    .setProvince(user.getProvince())
                    .setCity(user.getCity())
                    .setCounty(user.getCounty())
                    .setCommunity(user.getCommunity())
                    .setDistrict(user.getDistrict())
                    .setShopStatus(formSummary.getCheckStatus())
            ;
            this.shopsBaseInfoService.insert(shopsBaseInfo);
            formSummary.setShopsBaseInfoId(shopsBaseInfo.getId());
        }

    }

    @Override
    protected void beforeReGenPdf(Sqfw_completeflow completeFlow, Sqfw_formSummary_new formSummary, Map<String, Object> businessDataMap) {
        String paramData = formSummary.getParamData();
        // 重新生成数据
        buildFormSummary(formSummary);
        if (!paramData.equals(formSummary.getParamData())) {
            SqfwFormsummaryNewService formsummaryNewService = NutzIocUtils.getBean(SqfwFormsummaryNewService.class);
            Sqfw_formSummary_new summaryNew = formsummaryNewService.fetch(formSummary.getId());
            summaryNew.setParamData(formSummary.getParamData());
            formsummaryNewService.updateIgnoreNull(summaryNew);
        }
    }

}
